/*
 * @Description: Toolbar命令下拉按钮
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-11-27 13:37:00
 */

import { BaseCommand, Icon, useCommandManager } from '@amcax/base';
import { CaretUpOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
import i18n from 'i18next';
import { useRef, useState } from 'react';
import { ToolButton } from '../ToolButton';
import { StyledSplitToolButton } from '../styled';

interface IProps {
  cmds: BaseCommand[];
  className?: string;
  activated?: boolean;
}

export const SplitToolButton = ({
  cmds,
  className,
  activated = false,
}: IProps) => {
  const dropdownRef = useRef(null);
  const { invokeCmd } = useCommandManager();
  const [selectedCmd, setSelectedCmd] = useState(cmds[0]);
  const [open, setOpen] = useState(false);

  const handleMenuItemClick = (index: number) => {
    const cmd = cmds[index];
    setSelectedCmd(cmd);
    setOpen(false);
    invokeCmd(cmd);
  };

  const DropdownItems = () => {
    return (
      <div
        className='split-dropdown-wrapper'
        onMouseLeave={() => setOpen(false)}>
        <ul
          ref={dropdownRef}
          tabIndex={0}
          className={`split-dropdown ` + (className ?? '')}>
          {cmds.map((cmd, index) => {
            return (
              <Tooltip
                key={cmd.id}
                title={cmd.label ? i18n.t(cmd.label) : undefined}
                placement='right'>
                <li
                  onClick={() => handleMenuItemClick(index)}
                  style={{
                    padding: '3px',
                    cursor: 'pointer',
                  }}>
                  <Icon
                    name={cmd.icon}
                    size={20}
                    style={{ fontSize: '18px' }}
                  />
                </li>
              </Tooltip>
            );
          })}
        </ul>
      </div>
    );
  };

  return (
    <StyledSplitToolButton>
      <div
        style={{
          position: 'relative',
        }}>
        <ToolButton
          cmd={selectedCmd}
          className={className}
          activated={activated}
        />
        <CaretUpOutlined
          onMouseEnter={() => setOpen(!open)}
          style={{
            height: 'auto',
            position: 'absolute',
            bottom: '-4px',
            right: '-4px',
            transform: 'rotate(135deg)',
            fontSize: '12px',
          }}
        />
      </div>
      {open ? <DropdownItems /> : null}
    </StyledSplitToolButton>
  );
};
